/**

 @author 石头哥哥
 </P>
 Date:   2014/12/11
 </P>
 Time:   19:04

 注解：

 */
package {


import Qbase.utils.calculate.QFileUtil;
import Qbase.utils.sound.SoundManager;

import feathers.controls.Button;

import feathers.controls.List;

import feathers.controls.TextInput;
import feathers.controls.renderers.IListItemRenderer;
import feathers.data.ListCollection;
import feathers.layout.VerticalLayout;

import flash.desktop.NativeApplication;
import flash.display.Bitmap;
import flash.display.Shader;
import flash.events.Event;
import flash.filesystem.File;
import flash.geom.Point;
import flash.media.SoundTransform;
import flash.ui.Multitouch;

import lzm.starling.STLConstant;
import lzm.starling.STLRootClass;
import lzm.starling.swf.Swf;
import lzm.starling.swf.SwfAssetManager;
import lzm.starling.swf.display.SwfButton;
import lzm.starling.swf.display.SwfSprite;

import starling.animation.Transitions;
import starling.animation.Tween;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.display.MovieClip;
import starling.display.Shape;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
import starling.text.TextField;
import starling.textures.Texture;
import starling.textures.TextureSmoothing;
import starling.utils.Color;
import starling.utils.deg2rad;

import utils.Kit;

import view.TestRenderer;

public class GameRootTest extends STLRootClass {


    public function GameRootTest() {
        super();
        Swf.init(this);


        //init
        addEventListener(starling.events.Event.ADDED_TO_STAGE, init);    //init sprite container

        //获取焦点
        NativeApplication.nativeApplication.addEventListener(flash.events.Event.ACTIVATE, function (e:flash.events.Event):void {
            Starling.current.start();
        });
        //失去焦点
        NativeApplication.nativeApplication.addEventListener(flash.events.Event.DEACTIVATE, function (e:flash.events.Event):void {
            if (Multitouch.supportsTouchEvents) {
                Starling.current.stop();
            }
        });
    }

    /**
     * 加载资源
     * @param $e
     */
    private function init($e:starling.events.Event = null):void {
        GameSystem.swfAssetManager = new SwfAssetManager();
        GameSystem.swfAssetManager.verbose = true;
        GameSystem.assetManager = GameSystem.swfAssetManager.otherAssets;
        /**
         * 加载指定资源 path
         */
        var bitmapFileURLList:Array = QFileUtil.getAllFileUrlByDirectory(GameConstants.filePath, "shoot", ["png", "xml"]);
        GameSystem.swfAssetManager.enqueueOtherAssets(bitmapFileURLList);
        GameSystem.swfAssetManager.enqueue("test", [new File(GameConstants.filePath + "test")]);
        GameSystem.swfAssetManager.loadQueue(function (currentRatio:Number):void {
            if (currentRatio == 1) {
                removeEventListener(starling.events.Event.ADDED_TO_STAGE, init);


                //测试 feathers list
//                testList();
                testInput();

            }
        });
    }


    /**
     * 测试feathers list
     */
    private function testList():void {

        //  var dataArray:Array = [shape,shape,shape];


        var list:List = new List();

        //内部item 布局显示
        var layout:VerticalLayout = new VerticalLayout();
        layout.gap = 5;
        layout.scrollPositionVerticalAlign = VerticalLayout.VERTICAL_ALIGN_TOP;
        list.layout = layout;

        //位置 显示的大小
        list.x = Kit.midPoint(list).x;
        list.y = Kit.midPoint(list).y;
        list.width = STLConstant.StageWidth;
        list.height = 320;

        list.dataProvider = new ListCollection(
                [
                    { id: "测试1" },
                    { id: "测试2"},
                    { id: "测试3" },
                    { id: "测试4"},
                    { id: "测试5"},
                    { id: "测试6"},
                    { id: "测试7"},
                    { id: "测试8"},
                    { id: "测试9"}
                ]);


        list.itemRendererType = TestRenderer;

        addChild(list);

        /**
         *
         */
        list.addEventListener(starling.events.Event.CHANGE, function (e:starling.events.Event):void {
            var list:List = e.currentTarget as List;
            if (list) {
                trace("selectedIndex:", list.selectedIndex, "selecteditem", (list.selectedItem["id"]));
                list.selectedItem["id"] = "修改咯";
                list.dataProvider.updateItemAt(list.selectedIndex);   //
            }
        });


    }

    /**
     * 测试feathers输入框
     */
    private function testInput():void {

        var spr_chat:SwfSprite = GameSystem.swfAssetManager.getSwf("test").createSprite("spr_chat");
        var min:Point = Kit.midPoint(spr_chat);
        spr_chat.x = min.x;
        spr_chat.y = min.y;
        addChild(spr_chat);

        var chart_send:SwfButton = spr_chat.getButton("chart_send");
        var textInput:TextInput = new TextInput();
        textInput.width = 232;
        textInput.height = 100;
        textInput.x = 65;
        textInput.y = 404;
        textInput.textEditorProperties.fontSize = 32;
        textInput.textEditorProperties.fontName = "隶书";
        textInput.textEditorProperties.color = Color.WHITE;
        textInput.textEditorProperties.border = true;
        textInput.textEditorProperties.multiline = false;
        textInput.textEditorProperties.length = 1024;
        textInput.text = "输入发送的消息";
        spr_chat.addChild(textInput); // add  parent container


        var textInput2:TextInput = new TextInput();
        textInput2.width = 720;
        textInput2.height = 100;
        textInput2.x = 137;
        textInput2.y = 255;
        textInput2.textEditorProperties.fontSize = 32;
        textInput2.textEditorProperties.fontName = "隶书";
        textInput2.textEditorProperties.color = Color.WHITE;
        textInput2.textEditorProperties.border = true;
        textInput2.textEditorProperties.multiline = false;
        textInput2.textEditorProperties.displayAsPassword = true;
        textInput2.text = "输入发送的消息";
        spr_chat.addChild(textInput2); // add  parent container

        chart_send.addEventListener(TouchEvent.TOUCH, function (e:TouchEvent):void {
            var touch:Touch = e.getTouch((e.currentTarget as SwfButton), TouchPhase.ENDED);
            if (touch) {
                trace("send message :" + textInput.text);
            }
        });
    }


    /**
     * 测试动画 mc
     */
    private function testEnemyMC():void {

//        var quard:Quad = new Quad(STLConstant.StageWidth, STLConstant.StageHeight);
//        addChild(quard);

        /**
         * 添加背景
         */
        var firstImg:Image = new Image(GameSystem.assetManager.getTexture("background"));
        firstImg.width = STLConstant.StageWidth;
        firstImg.height = STLConstant.StageHeight;
        firstImg.smoothing = TextureSmoothing.NONE;
        addChild(firstImg);

        var secondImg:Image = new Image(GameSystem.assetManager.getTexture("background"));
        secondImg.width = STLConstant.StageWidth;
        secondImg.height = STLConstant.StageHeight;
        secondImg.y = -STLConstant.StageHeight;
        secondImg.smoothing = TextureSmoothing.NONE;
        addChild(secondImg);


        var testAnimation1:BgAnimatable = new BgAnimatable(firstImg, 10);
        var testAnimation2:BgAnimatable = new BgAnimatable(secondImg, 10);

        //测试 刷新  背景动画
        Starling.juggler.add(testAnimation1);
        Starling.juggler.add(testAnimation2);


        /**
         * 停止动画        1280
         */
//        var stopButton:SwfButton = GameSystem.swfAssetManager.createButton("btn_define");
//        stopButton.x = (STLConstant.StageWidth - stopButton.width) / 2;
//        stopButton.y = 840;
//        addChild(stopButton);
//        stopButton.addEventListener(starling.events.Event.TRIGGERED, function (e:starling.events.Event):void {
//            if (Starling.current.isStarted) {
//                //  Starling.current.stop();
//            } else {
//            }
//        });


        var mc_enemy_down:MovieClip = new MovieClip(GameSystem.assetManager.getTextures("enemy1_down"));
        mc_enemy_down.x = (STLConstant.StageWidth - mc_enemy_down.width) / 2;
        mc_enemy_down.y = (STLConstant.StageHeight - mc_enemy_down.height) / 2;
        addChild(mc_enemy_down);
        Starling.juggler.add(mc_enemy_down);


        //gameloading
        var mc_loading:MovieClip = new MovieClip(GameSystem.assetManager.getTextures("game_loading"));
        mc_loading.x = (STLConstant.StageWidth - mc_loading.width) / 2;
        mc_loading.y = 940;
        addChild(mc_loading);
        Starling.juggler.add(mc_loading);
        /**
         * 动作完成  销毁对象
         */
        mc_loading.addEventListener(starling.events.Event.COMPLETE, function (e:starling.events.Event):void {
            trace("[GameRoot]", "clear loading resource");
            removeChild(mc_loading);
            mc_loading.removeEventListeners(starling.events.Event.COMPLETE);
        });


        //play sound

        var transform:SoundTransform = new SoundTransform();
        transform.volume = 1;
        SoundManager.getInstance().playMusic("sound/game_music.mp3");


        //add enemy
        EnemyManager.getInstance().start(GameSystem.root);


        /**
         *
         */
        var result0:Vector.<Texture> = new Vector.<Texture>();
        for (var i:int = 1; i <= 2; ++i) {
            result0.push(GameSystem.assetManager.getTexture("hero" + i))
        }
        var mc_hero_flash:MovieClip = new MovieClip(result0);
        mc_hero_flash.x = (STLConstant.StageWidth - mc_hero_flash.width) / 2;
        mc_hero_flash.y = 940;

        addChild(mc_hero_flash);
        Starling.juggler.add(mc_hero_flash);


        Starling.juggler.delayCall(function ():void {
            //do something
        }, 1);

        /**
         *  register touch event
         */
        this.addEventListener(TouchEvent.TOUCH, function (touchEvent:TouchEvent):void {

            // get all touch event
            var touch:Touch = touchEvent.getTouch(touchEvent.currentTarget as DisplayObject, TouchPhase.MOVED);
            if (touch && touch.phase == TouchPhase.MOVED) {
                var obj:DisplayObject = touchEvent.currentTarget as DisplayObject;
                trace(touch.phase);
                trace("x:" + touch.globalX + " y:" + touch.globalY);

                var deletPoint:Point = touch.getLocation(obj).subtract(touch.getPreviousLocation(obj));
                mc_hero_flash.x = mc_hero_flash.x + deletPoint.x;
                mc_hero_flash.y = mc_hero_flash.y + deletPoint.y;
                /**
                 * 防止越界
                 */
                Kit.clame(mc_hero_flash);
            }
        });
    }

    /**
     * 测试处理
     */
    private function test():void {
        GameSystem.swfAssetManager.enqueue("test", [new File(GameConstants.filePath + GameConstants.testSwf)]);
        GameSystem.swfAssetManager.loadQueue(function ($ratio:Number):void {
            trace("loading " + (uint($ratio * 100)) + "%");
            if ($ratio == 1) {

                var sp:SwfSprite = GameSystem.swfAssetManager.getSwf("test").createSprite("spr_testPanel");
                sp.x = (STLConstant.StageWidth - sp.width) / 2;
                sp.y = (STLConstant.StageHeight - sp.height) / 2;

                var pivotX:Number = sp.pivotX;
                var pivotY:Number = sp.pivotY;


                addChild(sp);


                var nameTextfiled:TextField = new TextField(100, 100, "测试字体动画");

                nameTextfiled.color = Color.RED;
                nameTextfiled.fontSize = 20;

                nameTextfiled.x = (STLConstant.StageWidth - nameTextfiled.width) / 2;
                nameTextfiled.y = (STLConstant.StageHeight - nameTextfiled.height) / 2;
                sp.addChild(nameTextfiled);


                var btn_define:SwfButton = sp.getButton("queding");
                btn_define.addEventListener(starling.events.Event.TRIGGERED, function (e:starling.events.Event):void {
                    trace("确定按钮" + e.currentTarget);

                    /**
                     * tween 测试处理
                     */
                    var tween:Tween = new Tween(nameTextfiled, 2.0, Transitions.EASE_IN_OUT);
                    tween.animate("x", nameTextfiled.x + 50);
                    tween.animate("rotation", deg2rad(45));
                    // tween.fadeTo(0);
                    Starling.juggler.add(tween);

                    removeChild(sp, true);

                    testEnemyMC();

                });

                var quxiao_btn:SwfButton = sp.getButton("quxiao");
                quxiao_btn.addEventListener(starling.events.Event.TRIGGERED, function (e:starling.events.Event):void {
                    var btn:SwfButton = e.currentTarget as SwfButton;
                    trace("取消按钮" + e.currentTarget);
//                    var tween:Tween = new Tween(nameTextfiled, 2.0, Transitions.EASE_IN_OUT);
//                    tween.animate("x", nameTextfiled.x - 50);
//                    tween.animate("rotation", deg2rad(-45));
//                    tween.reverse = true;
//                    //tween.fadeTo(1);
//                    Starling.juggler.add(tween);
//


                    removeChild(sp, true);

                });

            }
        });
    }


}
}
